from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
# web驱动
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager


import time

class BrowserUtil:
    '''自动化登录的操作'''
    def __init__(self, browser) -> None:
        self.browser = browser
        pass

    @staticmethod
    def get_browser(type, driverPath):
        ''' 获取浏览器对象，确保电脑安装了该浏览器，且安装了浏览器驱动。
            type支持: edge、chrome、ie'''
        driver = None
        if type == 'edge':
            # 设置不自动关闭浏览器
            option = webdriver.EdgeOptions()
            option.add_experimental_option("detach", True)
            service = Service(executable_path=driverPath)
            driver = webdriver.Edge(option, service)
            driver.maximize_window()
        elif type == 'chrome':
            # 设置不自动关闭浏览器
            option = webdriver.ChromeOptions()
            option.add_experimental_option("detach", True)
            service = Service(executable_path=driverPath)
            driver = webdriver.Chrome(option, service)
            driver.maximize_window()
        else:
            print("目前仅支持type=edge/chrome两个浏览器")
        return driver
    
    @staticmethod
    def get_browser_service(type):
        ''' 获取浏览器对象,使用服务托管驱动：type支持: edge、chrome、ie'''
        driver = None
        if type == 'edge':
            # 设置不自动关闭浏览器
            option = webdriver.EdgeOptions()
            option.add_experimental_option("detach", True)
            service=Service(executable_path=EdgeChromiumDriverManager().install())
            driver = webdriver.Edge(option, service)
            driver.maximize_window()
        elif type == 'chrome':
            # 设置不自动关闭浏览器
            option = webdriver.ChromeOptions()
            option.add_experimental_option("detach", True)
            service=Service(executable_path=ChromeDriverManager().install())
            driver = webdriver.Chrome(option, service)
            driver.maximize_window()
        else:
            print("目前仅支持type=edge/chrome两个浏览器")
        return driver

    @staticmethod
    def close_browser(browser):
        '''关闭浏览器'''
        # 关闭浏览器
        browser.quit()

    def wait_loads(self, xpath, url=None):
        '''打开界面，并且确定加载完成。'''
        if url:
            self.browser.get(url)
        time.sleep(0.5)
        
        isOk = False
        while not isOk:
            try:
                el = WebDriverWait(self.browser, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
                print(el)
                if el:
                    isOk = True
            except Exception as ex:
                isOk = False

    def auto_form_xpath(self, fromValues):
        '''传入字典，自动完善表单内容, 字典格式：{'xpath':'value'}'''
        for xpath,value in fromValues.items():
            print(xpath)
            print(value)
            input_creditCode = self.browser.find_element(By.XPATH, xpath)
            input_creditCode.send_keys(value) 

    def auto_form_clsSelector(self, fromValues):
        '''传入字典，自动完善表单内容, 字典格式：{'selector':'value'}'''
        for selector,value in fromValues.items():
            input_creditCode = self.browser.find_element(By.CSS_SELECTOR, selector)
            input_creditCode.send_keys(value)
            time.sleep(0.1)

    def slider_opt(self, xpath, offset):
        '''找到滑块，并进行拖动'''
        # 获取拖拽的滑动验证码块 
        sliderbar = self.browser.find_element(By.XPATH, xpath)
        # 鼠标点击滑动块不松开
        ActionChains(self.browser).click_and_hold(sliderbar).perform()
        # 将圆球滑至相对起点位置的 右边xx
        ActionChains(self.browser).move_by_offset(xoffset=offset, yoffset=0).perform()
        # 放开滑动块
        time.sleep(0.5)
        ActionChains(self.browser).release(sliderbar).perform()
        time.sleep(0.1)

    def button_click(self, xpath):
        '''点击按钮'''
        btn = self.browser.find_element(By.XPATH, xpath)
        btn.click()
        time.sleep(0.1)
